<%= lines(autogen_notice(:go, pwd)) -%>

package google

import (
  "fmt"
  "testing"
  "strings"
  "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
  "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
  "github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

<%
sweeper_name = product_ns + object.name
wrap_path = object&.nested_query&.keys&.first || object.collection_url_key
listUrlTemplate = object.__product.base_url + object.base_url

listUrlTemplate.sub! "zones/{{zone}}", "aggregated"
aggregatedList = listUrlTemplate.include? "/aggregated/"

deleteUrlTemplate = object.__product.base_url + object.delete_uri
delete_id = deleteUrlTemplate.include? "_id"
-%>

func init() {
	resource.AddTestSweepers("<%= sweeper_name -%>", &resource.Sweeper{
		Name: "<%= sweeper_name -%>",
		F:    testSweep<%= sweeper_name -%>,
	})
}

// At the time of writing, the CI only passes us-central1 as the region
func testSweep<%= sweeper_name -%>(region string) error {
	resourceName := "<%= sweeper_name -%>"
	log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s",resourceName)

	config, err := sharedConfigForRegion(region)
	if err != nil {
		log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err)
		return err
	}

	err = config.LoadAndValidate(context.Background())
	if err != nil {
		log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err)
		return err
	}

	t := &testing.T{}
	billingId := getTestBillingAccountFromEnv(t)

	// Setup variables to replace in list template
	d := &ResourceDataMock{
		FieldsInSchema: map[string]interface{}{
			"project":config.Project,
			"region":region,
			"location":region,
			"zone":"-",
			"billing_account":billingId,
		},
	}

	listTemplate := strings.Split("<%= listUrlTemplate -%>","?")[0]
	listUrl, err := replaceVars(d, config, listTemplate)
	if err != nil {
		log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err)
		return nil
	}

	res, err := sendRequest(config, "GET", config.Project, listUrl, config.userAgent, nil)
	if err != nil {
		log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err)
		return nil
	}

	resourceList, ok := res["<%= wrap_path -%>"]
	if !ok {
		log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.")
		return nil
	}
	<%  if aggregatedList -%>
	var rl []interface{}
	zones := resourceList.(map[string]interface{})
	// Loop through every zone in the list response
	for _, zonesValue := range zones {
		zone := zonesValue.(map[string]interface{})
		for k, v := range zone {
			// Zone map either has resources or a warning stating there were no resources found in the zone
			if k != "warning" {
				resourcesInZone := v.([]interface{})
				rl = append(rl, resourcesInZone...)
			}
		}
	}
	<%  else -%>

	rl := resourceList.([]interface{})
	<% end -%>

	log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName)
	// Keep count of items that aren't sweepable for logging.
	nonPrefixCount := 0
	for _, ri := range rl {
		obj := ri.(map[string]interface{})
		<% if delete_id -%>
		var name string
		// Id detected in the delete URL, attempt to use id.
		if obj["id"] != nil {
			name = GetResourceNameFromSelfLink(obj["id"].(string))
		} else if obj["name"] != nil {
			name = GetResourceNameFromSelfLink(obj["name"].(string))
		} else {
			log.Printf("[INFO][SWEEPER_LOG] %s resource name and id were nil", resourceName)
			return nil
		}
		<% else -%>
		if obj["name"] == nil {
			log.Printf("[INFO][SWEEPER_LOG] %s resource name was nil", resourceName)
			return nil
		}

		name := GetResourceNameFromSelfLink(obj["name"].(string))
		<% end -%>
		// Skip resources that shouldn't be sweeped
		if !isSweepableTestResource(name) {
			nonPrefixCount++
			continue
		}

		deleteTemplate := "<%= deleteUrlTemplate -%>"
		<%  if aggregatedList -%>
		if obj["zone"] == nil {
			log.Printf("[INFO][SWEEPER_LOG] %s resource zone was nil", resourceName)
			return nil
		}
		zone := GetResourceNameFromSelfLink(obj["zone"].(string))
		deleteTemplate = strings.Replace(deleteTemplate, "{{zone}}", zone, -1)

		<% end -%>
		deleteUrl, err := replaceVars(d, config, deleteTemplate)
		if err != nil {
			log.Printf("[INFO][SWEEPER_LOG] error preparing delete url: %s", err)
			return nil
		}
		deleteUrl = deleteUrl+name

		// Don't wait on operations as we may have a lot to delete
		_, err = sendRequest(config, "DELETE", config.Project, deleteUrl, config.userAgent, nil)
		if err != nil {
			log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err)
		} else {
			log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name)
		}
	}

	if nonPrefixCount > 0 {
		log.Printf("[INFO][SWEEPER_LOG] %d items were non-sweepable and skipped.", nonPrefixCount)
	}

	return nil
}
